﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Zhao.Common;
using Zhao.Common.EnumEntity;
using Zhao.Models.Entity;

namespace Zhao.Arena.Utility.InitDatabaseExt
{
    /// <summary>
    /// 是否初始化数据库
    /// </summary>
    public static class InitDatabaseExt
    {
        /// <summary>
        /// 是否初始化数据库
        /// </summary>
        /// <param name="builder"></param>
        /// <exception cref="Exception"></exception>
        public static void InitDatabase(this WebApplicationBuilder builder)
        {
            #region 首页菜单 
            List<Menus> menuList = new List<Menus>();

            #endregion

            #region 获取控制上的特性标注(叶节点)
            Assembly asm = Assembly.GetExecutingAssembly();
            var controlleractionlist = asm.GetTypes()
                    .Where(type => typeof(ControllerBase)
                    .IsAssignableFrom(type));

            foreach (var controller in controlleractionlist)
            {
                if (controller.IsDefined(typeof(FunctionAttribute), true))
                {
                    FunctionAttribute? attribute = controller.GetCustomAttribute<FunctionAttribute>();
                    Guid guid = Guid.NewGuid();
                    Menus sysMenu = new Menus()
                    {
                        Id = guid,
                        ParentId = default,
                        MenuText = attribute?.GetDescription(),
                        Icon = "Tools",
                        WebUrlName = attribute?.GetWebURL(),
                        WebUrl = $"/{attribute?.GetWebURL()}",
                        VueFilePath = attribute?.GetVuePath(),
                        IsLeafNode = true,
                        Status = (int)StatusEnum.Normal,
                        CreateTime = DateTime.Now,
                    };

                    menuList.Add(sysMenu);

                    #region 获取方法上的特性标记(是子节点标记在控制器上的才是叶节点)
                    var mehtodlist = controller.GetMethods()
                         .Where(m => m.IsDefined(typeof(FunctionAttribute), true));

                    foreach (var method in mehtodlist)
                    {
                        FunctionAttribute? childAttribute = method.GetCustomAttribute<FunctionAttribute>();

                        if (childAttribute != null)
                        {
                            Guid guidaAc = Guid.NewGuid();
                            Menus sysMenuAc = new Menus()
                            {
                                Id = guidaAc,
                                ParentId = default,
                                MenuText = childAttribute?.GetDescription(),
                                Icon = "Tools",
                                WebUrlName = childAttribute?.GetWebURL(),
                                WebUrl = $"/{childAttribute?.GetWebURL()}",
                                VueFilePath = childAttribute?.GetVuePath(),
                                IsLeafNode = false,
                                Status = (int)StatusEnum.Normal,
                                CreateTime = DateTime.Now,
                            };
                            menuList.Add(sysMenuAc);
                        }
                    }
                    #endregion
                }
            }
            #endregion


            string? connectionString = builder.Configuration.GetConnectionString("ConnectionString");
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new Exception("请配置数据库链接字符串~");
            }

            ConnectionConfig connection = new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                ConnectionString = connectionString
            };
            using (SqlSugarClient client = new SqlSugarClient(connection))
            {

                #region 表初始化
                //判断菜单表是否存在 如果存在就删除重新创建（如果不用就注销） 
                //通过反射 获取ddl文件 拿到model进行表的创建
                //client.DbMaintenance.CreateDatabase();
                //if (client.DbMaintenance.IsAnyTable("Menus", false))
                //{
                //    client.DbMaintenance.DropTable("Menus");
                //}
                //Assembly assembly = Assembly.LoadFile(Path.Combine(AppContext.BaseDirectory, "Zhaoxi.Manage.Models.dll"));
                //Type[] typeArray = assembly.GetTypes()
                //    .Where(t => !t.Name.Equals("Sys_BaseModel") && t.Namespace.Equals("Zhaoxi.Manage.Models.Entity"))
                //    .ToArray();

                //client.CodeFirst.InitTables(typeArray);
                #endregion

                client.Insertable(menuList).ExecuteCommand();
            }

        }
    }
}
